<?php
namespace Home\Model;

use Think\Model;
class UserModel extends Model{
    //自动验证
    protected $_validate = array(
        //帐号名称2-20位
        array('accounts','2,20','帐号名称长度不合法',self::EXISTS_VALIDATE,'length',self::MODEL_INSERT),

        //帐号被占用
        array('accounts','','帐号名称被占用',self::EXISTS_VALIDATE,'unique',self::MODEL_INSERT),

        //帐号密码6-30位  后台 帐号新增
        array('password','6,30','帐号密码长度不合法',self::EXISTS_VALIDATE,'length',self::MODEL_INSERT),

        //帐号密码6-30位  后台 帐号修改
        array('password','6,30','帐号密码长度不合法',self::VALUE_VALIDATE,'length',self::MODEL_UPDATE),

        //确认密码和密码不一致 login 前台
        //确认密码和密码不一致 后台  修改密码
        array('password','notpassword','确认密码和密码不一致',self::EXISTS_VALIDATE,'confirm',self::MODEL_BOTH),


        // login  登录帐号验证
        array('accounts','2,20','登录帐号长度不合法',self::EXISTS_VALIDATE,'length',4),
        // login  登录密码验证
        array('password','6,30','登录密码长度不合法',self::EXISTS_VALIDATE,'length',4),


    );

    public function getList($sort,$order,$page,$rows,$keywords,$dateType,$dateFrom,$dateTo,$state) {

        $map = array();
        if ($keywords) {
            $map['accounts'] = array('like','%'.$keywords.'%');
        }
        if ($state) {
            $map['state'] = $state;
        }


        if ($dateFrom && $dateTo) {
            $map["$dateType"] = array(
                array('egt', $dateFrom),
                array('elt', $dateTo),
                );

        } else if ($dateFrom) {
            $map["$dateType"] = array('egt', $dateFrom);
        } else if ($dateTo) {
            $map["$dateType"] = array('elt', $dateTo);
        }

        //得到所有的节点
        $object = $this -> field('id,accounts,staff_name,last_login_time,last_login_ip,login_count,state,create_time')
                        -> where($map)
                        -> order(array($sort=>$order))
                        -> limit($rows * ($page-1) , $rows)
                        -> select();
        return array(
            'total' => $this->count(),
            'rows' => $object ? $object : ''
        );

    }

    //前后台  新增帐号操作[not=1 是login 前台新增帐号操作]
    public function register($accounts,$password,$staff_id=0,$staff_name='',$notpassword='',$state='',$tel='',$not = 0) {
        $addData = array(
            'accounts'       => $accounts,
            'password'       => $password,
            'staff_name'     => $staff_name,
            'notpassword'    => $notpassword,
            'tel'            => $tel,
            'state'          => $state ? $state : '正常',
            'create_time'    => getTime()
        );

        if($not == 0) {
            unset($addData['password']);
            unset($addData['notpassword']);
            unset($addData['tel']);
        }


        if ($this->create($addData)) {
            $addData['password'] = sha1($password);
            $id =  $this->add($addData);
            if($id) {
                $map['id'] = $staff_id;
                M('Staff')->where($map)->save(array('user_id'=>$id));
            }

            return $id ? $id : 0;

        } else{
            if ($this->getError() == '帐号名称被占用') {
                return -1;
            }
            return $this->getError();
        }
    }
    //根据ID 获取一条编辑的数据
    public function getOne($id) {
        $map['id'] = $id;
        return $this->field('id,accounts,staff_name,last_login_time,last_login_ip,login_count,state,create_time')->where($map)->find();
    }

    //根据ID 修改一条数据 [返回影响的行数]
    public function update($id,$password,$state,$notpassword='',$staff_id,$staff_name) {
        $updateData = array(
            'id'=>$id,
            'password'=>$password,
            'notpassword'=>$notpassword,
            'state'=>$state
        );



        if ($this->create($updateData)) {
            if (empty($password)) {
                unset($updateData['password']);
                unset($updateData['notpassword']);
            } else {
                $updateData['password'] = sha1($password);
            }

            if (is_numeric($staff_id)) {
                $updateData['staff_name'] = $staff_name;
                //原本的清零
                M('Staff')->where(array('user_id'=>$id))->setField(array('user_id'=>0));
                //现在的赋值
                M('Staff')->where(array('id'=>$staff_id))->setField(array('user_id'=>$id));

            }
            $id = $this->save($updateData);
            return $id ? $id : 0;
        } else {
            return $this->getError();
        }
    }

    //根据ID 修改当前登录密码 [返回影响的行数]
    public function editPassword($id,$password='',$notpassword='') {
        $updateData = array(
            'id'=>$id,
            'password'=>$password,
            'notpassword'=>$notpassword,
        );
        if ($this->create($updateData)) {
            if (empty($password)) {
                return -1;
            } else {
                $updateData['password'] = sha1($password);
            }

            $id = $this->save($updateData);
            return $id ? $id : 0;
        } else {
            return $this->getError();
        }
    }

    //根据ID 删除一条或者多条数据 [返回影响的行数]
    public function remove($ids) {
        $affectRow = $this->delete($ids);
        if ($affectRow) {
            //单个或批量删除帐号后，将档案记录清零
            $map['user_id'] = array('in',$ids);
            M('Staff')->where($map)->save(array('user_id'=>0));
        }
        return $affectRow;
    }

    //根据状态 state 进行审核
    public function state($id,$state) {
       $stateData = array(
           'id' => $id,
           'state' => $state
       );
        return $this->save($stateData);
    }


    //验证登录
    public function checkUser($accounts,$password) {
        $checkData = array(
            'accounts' => $accounts,
            'password' => $password
        );

        if($this->create($checkData,4)) {
            $map = array(
                'accounts' => $accounts,
                'password' => sha1($password)
            );

            $object =  $this->field('id,accounts,state')->where($map)->find();

            if ($object) {
                //返回 -1 登录帐号被冻结
                if ($object['state'] == '冻结') return -1;

                //登录成功 写入session
                session('admin',array(
                    'id' => $object['id'],
                    'accounts' => $object['accounts'],
                ));
                //更新登录 数据
                $updateData = array(
                    'id' => $object['id'],
                    'last_login_time'=>getTime(),
                    'last_login_ip'=> get_client_ip(),
                    'login_count' => array('exp','login_count+1')
                );
                //更新登录 入库
                $this->save($updateData);

                //返回 登录ID
                return $object['id'];

            } else {
                //返回 0  登录帐号或密码不正确
                return 0;
            }
        } else {
            return $this->getError();
        }

    }

}
